#include <iostream>
#include <signal.h>
#include <unistd.h>

void AddSig(sigset_t *set, int signo)
{
    int n = sigaddset(set, 2);
    if (n == -1)
    {
        perror("sigaddset error!");
        exit(1);
    }
}
void SetBlock(int how, sigset_t *newBlock, sigset_t *oldBlock)
{
    int n = sigprocmask(SIG_BLOCK, newBlock, oldBlock);
    if (n == -1)
    {
        perror("sigprocmask error!");
        exit(2);
    }
}
void PrintPending(sigset_t s)
{
    for (int i = 31; i > 0; --i)
    {
        if (sigismember(&s, i))
        {
            std::cout << "1";
        }
        else
        {
            std::cout << "0";
        }
    }
    std::cout << std::endl;
}
void handler(int signo)
{
    std::cout << "get a signal : " << signo << std::endl;
    exit(0);
}
int main()
{
    // 先处理要设置进内核信号屏蔽字的信号集
    sigset_t newBlock, oldBlock;
    AddSig(&newBlock, 2);
    // 把2号SIGINT设置进内核信号屏蔽字
    SetBlock(SIG_BLOCK, &newBlock, &oldBlock);
    // 向当前进程发送2号信号，发送前后打印Pending
    sigset_t pending;
    std::cout << "send before:" << std::endl;
    std::cout << "pending:" << std::endl << std::endl;
    sigpending(&pending);
    PrintPending(pending);
    kill(getpid(), 2);
    std::cout << "send after:" << std::endl;
    std::cout << "pending:" << std::endl;
    int cnt = 5;
    while (cnt--)
    {
        sigpending(&pending);
        PrintPending(pending);
        sleep(1);
    }
    //解除信号屏蔽，修改信号处理动作
    signal(2,handler);
    sigemptyset(&newBlock);
    sigprocmask(SIG_SETMASK,&newBlock,nullptr);
    return 0;
}
